package com.ruoyi.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        //在创建 ajax对象的时候会跳转到   request.js里面进行初始化  补上一个URL前缀
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        //判断是否开启验证
        ajax.put("captchaEnabled", captchaEnabled);
        //把后台生成的数据存储到ajax里面
        if (!captchaEnabled)
        {
            return ajax;//如果说没有开启后台的验证就直接跳过后面的步骤返回ajax即可

        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        //uuid

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
//         CAPTCHA_CODE_KEY   常量 用来配置后台redis里面的文件前缀id     key值等于redis里面的文件路径名+uuid
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();


            //用@进行分割前半段显示到前端的部分1+4？ 类似于     以@为界限提取前半部分
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            //code 是答案
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        //verifyKey就是key值  key值=uuid

        //将key值和答案存入redis里面
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
                                                            //最后两个表示限制和时间参数比如  倒数第二个是3  最后一个是Minutes那么最后意思就是时间限制是3分钟
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            //把前面的参数比如4+1写成一张图片传到前端  数据流os写成一张图片格式为jpg

            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);//存储图片和UUID
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
